package com.vip.mvc.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.internal.SystemPropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by cloudy.xie on 17/1/16.
 */
public class NettyHttpBootstrap {

    private static Logger logger = LoggerFactory.getLogger(NettyHttpBootstrap.class);

    private int port;

    private final int BOSS_POOL_SIZE = Runtime.getRuntime().availableProcessors() + 1;
    private EventLoopGroup boss = new NioEventLoopGroup(BOSS_POOL_SIZE,
            new DefaultThreadFactory("netty4http-boss-pool"));
    private EventLoopGroup worker = new NioEventLoopGroup(
            SystemPropertyUtil.getInt("events.workerThreads", 30),
            new DefaultThreadFactory("netty4http-worker-pool", Thread.MAX_PRIORITY));

    public NettyHttpBootstrap() {
    }

    public void connect() throws Exception {
        if (port <= 0) {
            logger.error("port为空,请先配置port");
            return;
        }

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)//设置封包 使用一次大数据的写操作，而不是多次小数据的写操作
                    .childOption(ChannelOption.MAX_MESSAGES_PER_READ, 36)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline p = socketChannel.pipeline();
                            p.addLast("http.decoder", new HttpRequestDecoder());
                            p.addLast("http.encoder", new HttpResponseEncoder());
                            p.addLast("http.request-handler", new NettyHttpJsonDispatchHandler());
                        }
                    });

            Channel ch = bootstrap.bind(port).sync().channel();
            logger.info(">>netty4http server startUp  [{}:{}]", ch.localAddress().toString(), port);

            ch.closeFuture().sync(); // blocked

        } finally {
            shutdown();
        }
    }

    protected void shutdown() {
        boss.shutdownGracefully();
        worker.shutdownGracefully();
    }

    public void setPort(int port) {
        this.port = port;
    }

}
